/**
 * 
 */
package com.ruyipu.forum.base;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.cookie.Cookie;
import org.apache.http.impl.cookie.BasicClientCookie;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

/**
 * @author donald
 * 
 */
public class LocalCookie {

	public static final String TAG = LocalCookie.class.getSimpleName();
	public static final String NAME = LocalCookie.class.getName();

	// 定义一些常量
	private static final String DATABASE_FILE = "cookies.db";
	private static final String COOKIES_TABLE_NAME = "cookies";
	private static final String COOKIES_NAME_COL = "name";
	private static final String COOKIES_VALUE_COL = "value";
	private static final String COOKIES_DOMAIN_COL = "domain";
	private static final String COOKIES_PATH_COL = "path";
	private static final String COOKIES_EXPIRES_COL = "expires";
	private static final String COOKIES_SECURE_COL = "secure";

	// 定义私有变量
	private SQLiteDatabase myDatabase = null;
	private Context context;

	private static LocalCookie myCookie;

	private LocalCookie(Context context) {
		this.context = context;
	}

	public static LocalCookie getInstance(Context context) {
		if (myCookie == null) {
			myCookie = new LocalCookie(context);
		}
		return myCookie;
	}

	private void openDatabase() {
		if (null != myDatabase && myDatabase.isOpen()) {
			return;
		}
		myDatabase = context.openOrCreateDatabase(DATABASE_FILE, 0, null);
		if (myDatabase != null) {
			myDatabase.execSQL("CREATE TABLE IF NOT EXISTS "
					+ COOKIES_TABLE_NAME + " (" + "_id INTEGER PRIMARY KEY, "
					+ COOKIES_NAME_COL + " TEXT, " + COOKIES_VALUE_COL
					+ " TEXT, " + COOKIES_DOMAIN_COL + " TEXT, "
					+ COOKIES_PATH_COL + " TEXT, " + COOKIES_EXPIRES_COL
					+ " TEXT, " + COOKIES_SECURE_COL + " INTEGER)");
			myDatabase.execSQL("CREATE INDEX IF NOT EXISTS cookiesIndex ON "
					+ COOKIES_TABLE_NAME + "(" + COOKIES_PATH_COL + ")");
		}
	}

	/**
	 * 往数据库中增加cookie
	 * 
	 * @author donald
	 * @param Cookie
	 *            cookie
	 * @return void
	 */
	public void addCookie(Cookie cookie) {
		openDatabase();

		if (cookie.getDomain() == null || cookie.getPath() == null
				|| cookie.getName() == null) {
			return;
		}
		String mCookieLock = "asd";
		synchronized (mCookieLock) {
			ContentValues cookieVal = new ContentValues();

			cookieVal.put(COOKIES_DOMAIN_COL, cookie.getDomain());
			cookieVal.put(COOKIES_PATH_COL, cookie.getPath());
			cookieVal.put(COOKIES_NAME_COL, cookie.getName());

			if (cookie.getExpiryDate() != null) {
				cookieVal.put(COOKIES_EXPIRES_COL, cookie.getExpiryDate()
						.toString());
			}

			cookieVal.put(COOKIES_VALUE_COL, cookie.getValue());
			myDatabase.insert(COOKIES_TABLE_NAME, null, cookieVal);
		}
	}

	public void addCookies(List<Cookie> cookies) {
		if (cookies.isEmpty()) {
			return;
		} else {
			int cookieSize = cookies.size();
			for (int i = 0; i < cookieSize; i++) {
				addCookie(cookies.get(i));
			}
		}
	}

	public void updateCookie(Cookie cookie) {
		openDatabase();
		ContentValues cv = new ContentValues();
		cv.put(COOKIES_DOMAIN_COL, cookie.getDomain());
		if (cookie.getExpiryDate() != null) {
			cv.put(COOKIES_EXPIRES_COL, cookie.getExpiryDate().toString());
		}

		cv.put(COOKIES_PATH_COL, cookie.getPath());
		cv.put(COOKIES_SECURE_COL, cookie.isSecure());
		cv.put(COOKIES_VALUE_COL, cookie.getValue());
		String args[] = { cookie.getName() };
		myDatabase
				.update(COOKIES_TABLE_NAME, cv, COOKIES_NAME_COL + "=?", args);
		Log.d(TAG, "update method called");
		return;
	}

	public List<Cookie> getCookies() {
		openDatabase();
		List<Cookie> cookies = new ArrayList<Cookie>();
		final Cursor result = myDatabase.rawQuery("SELECT * from "
				+ COOKIES_TABLE_NAME, null);
		if (result.getCount() < 1) {
			return null;
		}
		result.moveToFirst();
		while (!result.isAfterLast()) {
			BasicClientCookie myCookie = new BasicClientCookie(
					result.getString(result.getColumnIndex(COOKIES_NAME_COL)),
					result.getString(result.getColumnIndex(COOKIES_VALUE_COL)));
			String sDate = result.getString(result
					.getColumnIndex(COOKIES_EXPIRES_COL));
			if (sDate != null) {
				myCookie.setExpiryDate(GlobalUtil.cookieStringToDate(sDate));
			}

			myCookie.setDomain(result.getString(result
					.getColumnIndex(COOKIES_DOMAIN_COL)));
			myCookie.setPath(result.getString(result
					.getColumnIndex(COOKIES_PATH_COL)));
			boolean bSecure = result.getInt(result
					.getColumnIndex(COOKIES_SECURE_COL)) > 0 ? true : false;
			myCookie.setSecure(bSecure);

			result.moveToNext();
			cookies.add(myCookie);
		}
		return cookies;
	}

	public void closeDatabase() {
		myDatabase.close();
	}

	public void clearCookies() {
		openDatabase();
		myDatabase.execSQL("DELETE FROM " + COOKIES_TABLE_NAME);
		MyLog.d(TAG, "Cookie Cleared");
		closeDatabase();
	}
}
